const { executeQuery } = require('../config/dbConfig');

class ReportService {
  // 获取举报列表
  async getReportList() {
    const reports = await executeQuery(
      `SELECT r.*, p.title as post_title, 
       u1.nickname as report_user_name, 
       u2.nickname as reported_user_name 
       FROM reports r
       LEFT JOIN posts p ON r.post_id = p.id
       LEFT JOIN users u1 ON r.report_user_id = u1.id
       LEFT JOIN users u2 ON r.reported_user_id = u2.id
       ORDER BY r.created_at DESC`
    );

    return reports;
  }

  // 提交举报
  async submitReport(reportData) {

    const result = await executeQuery(
      `INSERT INTO reports (post_id, report_user_id, reported_user_id, 
        report_type, report_reason, status) 
       VALUES (?, ?, ?, ?, ?, 'pending')`,
      [
        reportData.postId,
        reportData.reportUserId,
        reportData.reportedUserId,
        reportData.reportType,
        reportData.reportReason
      ]
    );

    return result.insertId;
  }

  // 获取举报详情
  async getReportDetail(id) {
    const reports = await executeQuery(
      `SELECT r.*, p.title as post_title, 
       u1.nickname as report_user_name, 
       u2.nickname as reported_user_name 
       FROM reports r
       LEFT JOIN posts p ON r.post_id = p.id
       LEFT JOIN users u1 ON r.report_user_id = u1.id
       LEFT JOIN users u2 ON r.reported_user_id = u2.id
       WHERE r.id = ?`,
      [id]
    );

    return reports[0];
  }

  // 处理举报
  async handleReport(id, data) {
    await executeQuery(
      `UPDATE reports 
       SET status = 'processed', 
           handle_result = ?,
           handle_comment = ?,
           updated_at = CURRENT_TIMESTAMP 
       WHERE id = ? AND status = 'pending'`,
      [data.handleResult, data.handleComment || null, id]
    );

    return true;
  }
  

  // 驳回举报
  async rejectReport(id, rejectReason) {
    await executeQuery(
      `UPDATE reports 
       SET status = 'rejected', 
           reject_reason = ?,
           updated_at = CURRENT_TIMESTAMP 
       WHERE id = ? AND status = 'pending'`,
      [rejectReason, id]
    );

    return true;
  }

  // 删除举报
  async deleteReport(id) {
    await executeQuery(
      'DELETE FROM reports WHERE id = ?',
      [id]
    );

    return true;
  }
}


module.exports = new ReportService(); 